var version = '4.1.9'
var innerAudioContext = wx.createInnerAudioContext()

// get请求 url，参数，成功回调，未注册回调
function getRequest(interfaceStr, params, success, unregister_fun) {
  var app = getApp();
  if (app.globalData.token) {
    // params["shop_id"] = getApp().globalData.shop_id
    console.log(params)
    //有token 继续请求接口
    getRequestWithToken(interfaceStr, params, success)
  } else {
    console.log("没有token去登陆")
    console.log("app.globalData.token:", app.globalData.token);
    // 没有token 去登陆，登陆成功，登陆失败
    login({
      success: function(res) {
        console.log("开始登录")
        // params["shop_id"] = getApp().globalData.shop_id
        getRequestWithToken(interfaceStr, params, success)
      },
      fail: function(res) {
        wx.showToast({
          title: 'token获取失败',
        })
      }
    })
  }
}

function postRequest(interfaceStr, params, success) {
  var app = getApp()
  if (app.globalData.token) {
    // params["shop_id"] = getApp().globalData.shop_id
    postRequestWithToken(interfaceStr, params, success)
  } else {
    login({
      success: function(res) {
        // params["shop_id"] = getApp().globalData.shop_id
        postRequestWithToken(interfaceStr, params, success)
      },
      fail: function(res) {
        console.log(res)
        wx.showToast({
          title: 'token获取失败',
        })
      }
    })
  }
}

function getRequestWithToken(interfaceStr, params, success) {
  console.log(params)
  wx.showLoading({
    title: '加载中，请稍后',
  })
  var app = getApp()
  wx.request({
    method: 'GET',
    url: 'https://shop.hbsse.com/' + interfaceStr,
    data: params,
    header: {
      'Content-type': 'application/json; charset=UTF-8',
      'Authorization': 'Token ' + app.globalData.token,
      'version': version,
    },
    success: function(res) {
      console.log(res)
      wx.hideLoading()
      setTimeout(function() {
        wx.stopPullDownRefresh()
      }, 100)
      console.log(interfaceStr + ' 请求成功')
      if (res.data.status == 0) {
        console.log(res.data)
        success(res.data)
      } else if (res.data.status == 700){
        console.log(res)
        wx.showModal({
          title: '提示',
          content: res.data.detail,
          // success:function(){
          //   wx.navigateTo({
          //     url: '../login/login_in',
          //   })
          // }
        })
      }else{
        success(res.data)
      }
    },
    fail: function(res) {
      console.log(interfaceStr + ' 请求失败')
      console.log(res)
      setTimeout(function() {
        wx.stopPullDownRefresh()
      }, 100)
    }
  })
}

function login(obj) {
  console.log(obj);
  var app = getApp();
  wx.showLoading({
    title: '请求中，请稍待',
  })
  wx.login({
    success: res => {
      console.log(res)
      // 发送 res.code 到后台换取 openId, sessionKey, unionId
      if (res.code) {
        app.globalData.code = res.code
        var params = {}
        params['code'] = res.code
        console.log('code' + res.code)
        params['appid'] = app.globalData.appid
        wx.request({
          url: 'https://shop.hbsse.com/backend/shop/v1/admin/api/seller/wx/login',
          method: "POST",
          data: params,
          success: function(logRes) {
            console.log('登录成功')
            console.log(logRes)
            var status = logRes.data.status
            if (status == 0) {
              console.log("已注册，获取用户信息成功")
              app.globalData.token = logRes.data.detail.token;
              app.globalData.openid = logRes.data.detail.openid;
              app.globalData.owner = logRes.data.identity;
              wx.navigateTo({
                url: '/pages/index/index',
              });

            }else if(status == 204){
              console.log("获取用户和信息失败");
              wx.showModal({
                title: '提示',
                content: logRes.data.detail,
              })              
            }else if(status == 2){
              console.log("未注册")
              wx.showModal({
                title: '提示',
                content: logRes.data.detail,
              })              
            }
          }
        })
      } else {
        console.log('登录失败' + res.errMsg)
      }
    },
    fail: res => {
      console.log('登录失败')
      console.log(res)
    },
    complete: res => {
      console.log('登录接口调用完毕')
      wx.hideLoading()
    }
  })
}

function postRequestWithToken(interfaceStr, params, success) {
  wx.showLoading({
    title: '加载中，请稍后',
  })
  console.log(params)
  var app = getApp();
  wx.request({
    method: 'POST',
    url: 'https://shop.hbsse.com/' + interfaceStr,
    data: params,
    header: {
      'Content-type': 'application/json; charset=UTF-8',
      'Authorization': 'Token ' + app.globalData.token,
      'version': version
    },
    success: function(res) {
      console.log(res.data)
      console.log(interfaceStr + ' 请求成功')
      setTimeout(function() {
        wx.stopPullDownRefresh()
      }, 100)
      wx.hideLoading()
      if (res.data.status == 0) {
        console.log("成功")
        success(res.data)
      } else {
        console.log("失败")
        wx.showModal({
          title: '提示',
          content: res.data.detail,
        })
      }
    },
    fail: function(res) {
      console.log(interfaceStr + ' 请求失败')
      setTimeout(function() {
        wx.stopPullDownRefresh()
      }, 100)
      console.log(res)
    }
  })
}

function defaultParams() {
  var app = getApp()
  var params = {}
  params['openid'] = app.globalData.openid
  params['appid'] = app.globalData.appid
  return params
}

function shopParams() {
  var app = getApp()
  return {
    shop_id: app.globalData.shop_id
  }
}


/**
 * 
 * **/
function getAuthorization(successCallBack, failCallBack) {
  successCallBack()
}

function updateUserinfo(openid, iv, encryptedData, nick, gender, logo, success) {
  var params = defaultParams()
  params['openid'] = openid
  params['nick'] = nick
  params['sex'] = gender
  params['logo'] = logo
  params['iv'] = iv
  params['encrypted_data'] = encryptedData
  console.log(params)
  wx.showLoading({
    title: '加载中，请稍后'
  })
  console.log('注册')
  wx.request({
    method: 'POST',
    url: 'https://wx.extend.xuemei99.com/xcx/register',
    data: params,
    header: {
      'Content-type': 'application/json; charset=UTF-8',
      'version': version
    },
    success: function(res) {
      console.log(res)
      console.log('注册成功' + res)
      wx.hideLoading()
      if (res.data.status == 0) {
        success(res.data)
      } else {
        wx.showToast({
          title: res.data.detail,
          image: '/images/close.png',
        })
      }

    },
    fail: function(res) {
      wx.hideLoading()
      console.log(res)
      console.log(' 请求失败')
    }
  })
}

// 播放音频文件
function playVoice(url){
  innerAudioContext.autoplay = true
  innerAudioContext.src = url;
  innerAudioContext.play();
}

function getUserInformation(success) {
  getRequest('xcx/user/info', defaultParams(), function(res) {
    success(res.detail)
  })
}

///通过扫描小程序码获取的scene id（由后台创建二维码时提供）获取其对应的scene对应json数据
function getSceneFromMiniCodeBySceneID(sceneId, success) {
  getRequest('xcx/get/scene', {
    "scene_id": sceneId
  }, function(res) {
    console.log("===========================扫描二维码进入")
    console.log(res)
    success(res)
  })
}



var imageNames = []
var imageUrls = []
//多张图片上传
function uploadimg(data) {
  console.log(data)
  if (data.path.length == 0) {
    return
  }
  var i = data.i ? data.i : 0,
    success = data.success ? data.success : 0,
    fail = data.fail ? data.fail : 0;
  let app = getApp()
  wx.uploadFile({
    url: 'https://wx.extend.xuemei99.com/xcx/api/upload',
    filePath: data.path[i],
    name: 'file',
    formData: {
      "imageIndex": i
    },
    header: {
      'content-type': 'multipart/form-data',
      'Authorization': app.globalData.token,
      'version': version
    },
    success: (resp) => {
      console.log(resp)
      console.log("shangchaun success")
      success++;
      if (resp.statusCode == 200) {
        let data = JSON.parse(resp.data)
        console.log(data)
        imageUrls.push(data.path)
        imageNames.push(data.name)
      }
      //这里可能有BUG，失败也会执行这里
    },
    fail: (res) => {
      fail++;
      console.log('fail:' + i + "fail:" + fail);
    },
    complete: () => {
      console.log(i);
      i++;
      if (i == data.path.length) { //当图片传完时，停止调用
        console.log('执行完毕');
        console.log('成功：' + success + " 失败：" + fail);
        let totalImages = JSON.parse(JSON.stringify(imageUrls)) //深拷贝图片数组已被传出去。
        let totalImageNames = JSON.parse(JSON.stringify(imageNames))
        imageNames = [] ///清空全局变量，避免造成对后续操作的干扰
        imageUrls = []

        data.finished({
          "images": totalImages,
          'imageNames': totalImageNames,
          "failNum": fail
        })
      } else { //若图片还没有传完，则继续调用函数
        data.i = i;
        data.success = success;
        data.fail = fail;
        uploadimg(data);
      }
    }
  })
}

function requestForMusicList(success) {
  getRequest("klk/music/list", defaultParams(), function(res) {
    success(res)
  })
}


function requestToGetNotifications(success) {
  getRequest("klk/check/message", defaultParams(), function(res) {
    let obj = res.detail
    getApp().globalData.newApplications = obj.activity
    getApp().globalData.newMessages = obj.message
    if (obj.activity > 0) {
      wx.showTabBarRedDot({
        index: 3,
      })
    }
    if (obj.message > 0) {
      wx.setTabBarBadge({
        index: 2,
        text: String(obj.message),
      })
    }
    success(res)
  })
}


function getVersionCode() {
  return version
}

/**
 * 已註冊
 * **/
function rerigtered(obj, logRes) {
  getApp().globalData.token = logRes.data.detail.token,
    getApp().globalData.openid = logRes.data.detail.openid
  getApp().globalData.owner = logRes.data.detail.owner
  // getApp().globalData.shop_id = logRes.data.detail.shopId
  getApp().globalData.phone = logRes.data.detail.phone
  console.log(obj)
  obj.success(logRes)
}

/**
 * 未注册
 * 请求注册接口
 * **/
function unregistered(obj, logRes) {
  updateUserinfo(logRes.openid, logRes.iv, logRes.encryptedData, logRes.nickName, logRes.gender == true ? 0 : 1, logRes.avatarUrl, function(useInfoRes) {
    getApp().globalData.token = useInfoRes.token
    getApp().globalData.openid = useInfoRes.openid
    getApp().globalData.owner = useInfoRes.owner
    //  getApp().globalData.shop_id = logRes.data.detail.shopId
    getApp().globalData.user_authorization = true //授权状态
    obj.success(useInfoRes)
  })
}

/**
 * 封装点击授权，注册函数
 * **/
function user_authorization_fun(res, success_) {
  let that = this
  console.log("请求授权返回的res")
  console.log(res)
  if (res.detail.userInfo == undefined){
    wx.showToast({
      title: '授权失败，请重新授权',
      icon:"none"
    })
    wx.navigateBack({
      delta:-1
    })
  }else{
    let user_info = res.detail.userInfo;
    let open_id = getApp().globalData.openid; //openid
    let iv = res.detail.iv; //iv
    let encrypted_data = res.detail.encryptedData; //encryptedData
    let user_name = user_info.nickName; //name
    let gender = user_info.gender; //gender
    let avatarUrl = user_info.avatarUrl; //avatarUrl
    console.log(open_id)
    let logRes = {
      openid: open_id,
      iv: iv,
      encryptedData: encrypted_data,
      nickName: user_name,
      gender: gender,
      avatarUrl: avatarUrl
    }
    //授权成功之后回调，刷新数据
    let obj = {
      success: function (res) {
        success_(res)
      }
    }
    //请求注册接口
    unregistered(obj, logRes)
  }
}

/**
 * 分享判断是否为店家
 * **/
function ownerShare(successFun) {
  let isOwner = getApp().globalData.owner
  if (isOwner) {
    getRequest('xcx/share/shop', {}, function(res) {
      successFun(res.detail)
    })
  } else {
    successFun(getApp().globalData.shop_id)
  }
}

/**
 * 消息通知红点显示
 * **/
function message_notice(calback_success) {
  getRequest('xcx/dot/show', {}, function(res) {
    console.log(res)
    getApp().globalData.personal_notice = res.detail.dot_show
    getApp().globalData.activity_notice = res.detail.apply_dot_show
    getApp().globalData.recruit_notice = res.detail.recruitment_dot_show
    if (calback_success) {
      calback_success(res)
    }
  })
}

module.exports = {
  postRequest: postRequest,
  getRequest: getRequest,
  defaultParams: defaultParams,
  shopParams: shopParams,
  login: login,
  playVoice: playVoice,
  getAuthorization: getAuthorization,
  ///从后台的获取用户注册信息
  getUserInformation: getUserInformation,
  ///更新用户信息
  updateUserinfo: updateUserinfo,
  //通过扫描小程序码获取的scene id（由后台创建二维码时提供）获取其对应的json数据(由使用者自己定义的scene数据结构)
  getSceneFromMiniCodeBySceneID: getSceneFromMiniCodeBySceneID,
  ///获取音乐列表
  requestForMusicList: requestForMusicList,
  ///上传图片
  uploadimg: uploadimg,
  ///获取版本号
  getVersionCode: getVersionCode,
  ///获取消息及活动通知
  requestToGetNotifications: requestToGetNotifications,
  ///走已注册逻辑
  rerigtered: rerigtered,
  ///走未注册逻辑
  unregistered: unregistered,
  ///分享判断是否为商家
  ownerShare: ownerShare,

  ///消息通知红点显示
  message_notice: message_notice,

  //用户授权，请求注册
  user_authorization_fun: user_authorization_fun,
}